//
//  StoreGoodsDetailViewModel.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 16/4/13.
//  Copyright © 2016年 河南大实惠电子商务有限公司. All rights reserved.
//

#import "StoreGoodsDetailViewModel.h"
//untils
#import "Global.h"
#import "ManagerGlobeUntil.h"
#import "ManagerHttpBase.h"
#import "NSString+Conversion.h"
#import "UIImage+ColorToImage.h"
//vendor
#import "FMDBManager.h"
@interface StoreGoodsDetailViewModel ()
@property(nonatomic, strong)NSString *goodid;
@property(nonatomic, strong)NSString *isSelfGoods;
@property(nonatomic, strong)NSString *goodsType;
@property(nonatomic, strong)NSDictionary *dataSouceDic;
@end
@implementation StoreGoodsDetailViewModel
//请求商品详情
- (void)requestGoodsDetailDataWithGoodsId:(NSString*)goodsID isSelf:(NSString*)isSelf success:(void (^)(NSArray *responseObjects))success failure:(void(^)(NSString *failureMessage))failureMessage {
    self.goodid = goodsID;
    ManagerHttpBase *manager=[ManagerHttpBase sharedManager];
    NSMutableDictionary *parameters=[[NSMutableDictionary alloc]init];
    XiaoQuAndStoreInfoModel *xiaoQuAndStoreModel = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    [parameters setObject:[NSString stringISNull:xiaoQuAndStoreModel.storeID] forKey:@"STOREID"];
    [parameters setObject:goodsID forKey:@"GOODSID"];
    if ([ManagerGlobeUntil sharedManager].transactionLogin) {//返回是否收藏
        UserInfoModel *userModel = [[ManagerGlobeUntil sharedManager]getUserInfo];
        [parameters setObject:[NSString stringISNull:userModel.token] forKey:@"TOKEN"];
    }
    [parameters setObject:isSelf forKey:@"ISSELF"];
    [manager parameters:parameters customPOST:@"goods/detail" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dataDic = (NSDictionary*)responseObject;
            NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
            NSString *msg = [dataDic objectForKey:@"MSG"];
            if ([state isEqualToString:@"0"]) {//请求成功
                if ([[dataDic objectForKey:@"OBJECT"] count] != 0) {
                    NSArray *handleDataArr = [self handelGoodsDetailData:[dataDic objectForKey:@"OBJECT"]];
                    success(handleDataArr);
                } else {
                    success(@[]);
                }
            }else{
                if (msg.length != 0) {
                    failureMessage(msg);
                } else {
                    failureMessage(@"请求超时");
                }
            }
            
        }
        
        } failure:^(bool isFailure) {
            failureMessage(@"请求超时");
        }];
}
//添加关注
- (void)markGoodsWithGoodsId:(NSString*)goodsID isSelf:(NSString*)isSelf success:(void (^)(NSString *successMsg))success failure:(void(^)(NSString *failureMessage))failureMessage {
    UserInfoModel *userInfoMode = [[ManagerGlobeUntil sharedManager] getUserInfo];
    XiaoQuAndStoreInfoModel *xiaoQuAndStoreModel = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:[NSString stringISNull:userInfoMode.token] forKey:@"TOKEN"];
    [parameter setObject:goodsID forKey:@"GOODSID"];
    [parameter setObject:isSelf forKey:@"ISSELF"];
    [parameter setObject:serviceVersionNumber forKey:@"APIVERSION"];
    [parameter setObject:xiaoQuAndStoreModel.storeID forKey:@"STOREID"];
    [manager parameters:parameter customPOST:@"user/doCollect" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dataDic = (NSDictionary*)responseObject;
            NSString *msg = [dataDic objectForKey:@"MSG"];
            NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
            if ([state isEqualToString:@"0"]) {//请求成功
                msg = @"关注成功";
                self.markCount = [NSString stringWithFormat:@"%ld",self.markCount.integerValue + 1];
                self.isCollectedGoods = YES;
                success(msg);
            }else {//请求失败
                if (msg.length != 0) {
                    failureMessage(msg);
                } else {
                    failureMessage(@"关注失败");
                }
            }
        }
        
    } failure:^(bool isFailure) {
        
        failureMessage(@"请求超时");
    }];

}
//取消关注
- (void)cancelMarkGoodsWithGoodsId:(NSString*)goodsID success:(void (^)(NSString *successMsg))success failure:(void(^)(NSString *failureMessage))failureMessage {
    UserInfoModel *mode = [[ManagerGlobeUntil sharedManager] getUserInfo];
    ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:[NSString stringISNull:mode.token] forKey:@"TOKEN"];
    [parameter setObject:goodsID forKey:@"GOODSID"];
    [manager parameters:parameter customPOST:@"user/cancelCollect" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dataDic = (NSDictionary*)responseObject;
            NSString *msg = [dataDic objectForKey:@"MSG"];
            NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
            if ([state isEqualToString:@"0"]) {//请求成功
                msg = @"取消关注";
                self.isCollectedGoods =  NO;
                self.markCount = [NSString stringWithFormat:@"%ld",self.markCount.integerValue - 1];
                success(msg);
            }else {//请求失败
                if (msg.length != 0) {
                    failureMessage(msg);
                } else {
                    failureMessage(@"取消关注失败");
                }
            }
        }
        
    } failure:^(bool isFailure) {
        
        failureMessage(@"请求超时");
    }];
}
//把商品添加到购物车
- (void)addGoodsToShopingCart {
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    NSString *shopID = [NSString stringISNull:mode.storeID];
    NSString *goodID = self.goodid;
    NSString *name = [self.dataSouceDic objectForKey:@"NAME"];
    NSData *picture = UIImagePNGRepresentation(self.goodsLogo);
    NSString *type = [NSString stringTransformObject:[self.dataSouceDic objectForKey:@"TYPE"]];
    NSString *price = [NSString stringWithFormat:@"%.2f",[[NSString stringTransformObject:[self.dataSouceDic objectForKey:@"SELLPRICE"]] floatValue]];
    NSString *oldprice = [NSString stringWithFormat:@"%.2f",[[NSString stringTransformObject:[self.dataSouceDic objectForKey:@"MARKETPRICE"]] floatValue]];
    NSString *ischoose =@"1";
    if ([self.isSelfGoods isEqualToString:@"1"]) {//是否是自营商品：0：不是，1：是。
        shopID =@"";
    }
    NSMutableDictionary *goodSqlite=[[FMDBManager sharedManager]QueryDataWithShopID:shopID goodID:goodID];
    if (goodSqlite.count ==0) { //购物车没数据 先存
        NSString *buynum= @"1";
        [[FMDBManager sharedManager]InsertWithshopID:shopID goodID:goodID name:name Picture:picture type:type price:price oldprice:oldprice buynum:buynum ischoose:ischoose isProprietary:self.isSelfGoods];
        
    }else{//购物车有数据 更新数据
        
        NSString *str=[goodSqlite objectForKey:@"buynum"];
        if ([self.isSelfGoods isEqualToString:@"1"])
        {
            [[FMDBManager sharedManager]deleteOneDataWithgoodID:goodID];
        }else{
            [[FMDBManager sharedManager]deleteOneDataWithShopID:shopID goodID:goodID];
        }
        //字符串 变数字 然后加减完 变回字符串
        NSInteger buynum =str.integerValue;
        buynum++;
        NSString *srr=[NSString stringWithFormat:@"%ld",(long)buynum];
        [[FMDBManager sharedManager]InsertWithshopID:shopID goodID:goodID name:name Picture:picture type:type price:price oldprice:oldprice buynum:srr ischoose:ischoose isProprietary:self.isSelfGoods];
    }
}
#pragma mark -- 数据处理
- (NSArray *)handelGoodsDetailData:(NSDictionary*)dataDic  {
    self.dataSouceDic = dataDic;
    self.isHadTextAndImageDescribe = [self judgeGoodsIsHadTextAndImageDescribe:[NSString stringTransformObject:[dataDic objectForKey:@"HASDESCRIBE"]]];
    self.isCollectedGoods = [self goodsIsCollected:[NSString stringTransformObject:[dataDic objectForKey:@"ISCOLLECTED"]]];
    self.markCount = [NSString stringTransformObject:[dataDic objectForKey:@"COLLECTEDCOUNT"]];
    BOOL isSelfGoods = [self isSelfGoodsWithGoodsType:[NSString stringTransformObject:[dataDic objectForKey:@"ISSELF"]]];//是否直营商品
    BOOL isRebate = [self isReBateWithBateType:[NSString stringTransformObject:[dataDic objectForKey:@"ISREBATE"]]];//是否返现
    /************** 商品信息 **************/
    //商品标题
    NSString *goodsTitle = [self appendTitle:[NSString stringTransformObject:[dataDic objectForKey:@"NAME"]]
                              imageName:[self titleLogoWithIsSelfGoods:isSelfGoods isRebate:isRebate]];
    //商品简介
    NSString *goodsDescribe = [NSString stringTransformObject:[dataDic objectForKey:@"SHORTINFO"]];
    //销售量
    NSString *goodsSellCount = [NSString stringWithFormat:@"月销售量%ld份",(long)[[NSString stringTransformObject:[dataDic objectForKey:@"SALECOUNT"]] integerValue]];
    //关注数
    NSString *goodsMarkCount = [NSString stringWithFormat:@"关注%ld",(long)[self.markCount integerValue]];
    //现价
    NSString *goodsCurrentPrice = [NSString stringWithFormat:@"￥%.2f",[[NSString stringTransformObject:[dataDic objectForKey:@"SELLPRICE"]] floatValue]];
    //原价
    NSString *goodsOldPrice = [NSString stringWithFormat:@"￥%.2f",[[NSString stringTransformObject:[dataDic objectForKey:@"MARKETPRICE"]] floatValue]];
    NSDictionary *goodsInfo = @{@"title":goodsTitle,@"describe":goodsDescribe,@"saleCount":goodsSellCount,@"markCount":goodsMarkCount
                           ,@"currentPrice":goodsCurrentPrice,@"oldPrice":goodsOldPrice};
    
    /************** 返利推荐信息 **************/
    //是否自营商品 0：不是，1：是
    self.isSelfGoods = [NSString stringTransformObject:[dataDic objectForKey:@"ISSELF"]];
    //商品类型 1：普通，2：推荐，3：限量，4：一元购
    self.goodsType = [NSString stringTransformObject:[dataDic objectForKey:@"TYPE"]];
    NSDictionary *goodsRebateInfo = nil;
    if (isRebate) {//返利
        NSString *rebateContent = [self rebateOrRecommend:@"rebate" content:[NSString stringTransformObject:[dataDic objectForKey:@"PERCENT4"]] isRebate:isRebate];
        NSString *recommendContent = [self rebateOrRecommend:@"recommend" content:[NSString stringTransformObject:[dataDic objectForKey:@"PERCENT5"]] isRebate:isRebate];
        goodsRebateInfo = @{@"rebate":rebateContent,@"recommend":recommendContent};
    } else {//未返利
        NSString *recommendContent = [self rebateOrRecommend:@"recommend" content:@"15" isRebate:isRebate];
        goodsRebateInfo = @{@"recommend":recommendContent};
    }
    /************** 商品规格信息 **************/
    NSDictionary *goodsGuigeInfo = nil;
    NSString *goodsGuiGe = [NSString stringTransformObject:[dataDic objectForKey:@"SPEC"]];
    goodsGuigeInfo = @{@"guige":goodsGuiGe};
    
    /************** 商品轮播图片信息 **************/
    self.goodsLoopImages = [self handleLoopImagesDatas:[dataDic objectForKey:@"IMAGES"]];
    self.goodsLogo = [UIImage createImageWithImageUrlString:[NSString stringTransformObject:[dataDic objectForKey:@"THUMB"]]];
    if (self.goodsLogo==nil) {
        self.goodsLogo = [UIImage imageNamed:@"productDetail_Default"];
    }
    /*************  将浏览商品详情存入数据库  先查询再插入  **************/
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    NSString *shopID=[NSString stringISNull:mode.storeID];
    NSString *goodID=[NSString stringTransformObject:[dataDic objectForKey:@"ID"]];
    NSDictionary *goodSqlite=[[FMDBManager sharedManager]HistoryQueryDataWithShopID:shopID goodID:goodID serviceshopID:@""];
    if (goodSqlite.count ==0) {
        [[FMDBManager sharedManager]HistoryInsertWithshopID:shopID goodID:goodID Picture:UIImagePNGRepresentation(self.goodsLogo)
                                                       name:[NSString stringTransformObject:[dataDic objectForKey:@"NAME"]]
                                                      price:[NSString stringWithFormat:@"%.2f",[[NSString stringTransformObject:[dataDic objectForKey:@"SELLPRICE"]] floatValue]]
                                                   oldprice:[NSString stringWithFormat:@"%.2f",[[NSString stringTransformObject:[dataDic objectForKey:@"MARKETPRICE"]] floatValue]]
                                              serviceshopID:@""
                                          serciceshopdetail:@""
                                                sercvicenum:@"" isProprietary:[NSString stringTransformObject:[dataDic objectForKey:@"ISSELF"]]];
    }else
    {
        [[FMDBManager sharedManager]HistorymodifyDataWithShopID:shopID goodID:goodID
                                                           name:[NSString stringTransformObject:[dataDic objectForKey:@"NAME"]]
                                                          price:[NSString stringWithFormat:@"%.2f",[[NSString stringTransformObject:[dataDic objectForKey:@"SELLPRICE"]] floatValue]]
                                                       oldprice:[NSString stringWithFormat:@"%.2f",[[NSString stringTransformObject:[dataDic objectForKey:@"MARKETPRICE"]] floatValue]]
                                                  serviceshopID:@""
                                              serciceshopdetail:@"" sercvicenum:@"" isProprietary:[NSString stringTransformObject:[dataDic objectForKey:@"ISSELF"]]];
    }
    
    
    return @[@[goodsInfo,goodsRebateInfo],@[goodsGuigeInfo]];
}

//判断是否有图文详情
- (BOOL)judgeGoodsIsHadTextAndImageDescribe:(NSString*)isHasDescirpe {
    //是否有图文介绍，1：有，0：没有
    if ([isHasDescirpe isEqualToString:@"1"]) {
        return YES;
    }
    return NO;
}
//当前登录用户是否收藏该商品 1：是，0：否 ,只在用户登录时有效，其他情况下均为0
- (BOOL)goodsIsCollected:(NSString*)isCollected {
    if ([isCollected isEqualToString:@"1"]) {
        return YES;
    }
    return NO;
}
//是否是直营商品：0：不是，1：是
- (BOOL)isSelfGoodsWithGoodsType:(NSString*)goodsType {
    if ([goodsType isEqualToString:@"1"]) {
        return YES;
    }
    return NO;
}
//是否返利，0：不是，1：是
- (BOOL)isReBateWithBateType:(NSString*)bateType {
    if ([bateType isEqualToString:@"1"]) {
        return YES;
    }
    return NO;
}
//根据不同类型返回不同图片
- (NSString*)titleLogoWithIsSelfGoods:(BOOL)isSelfGoods isRebate:(BOOL)isRebate {
    if (isRebate && isSelfGoods) {//自营并返现
        return @"[hongziying] [fanxian] ";
    }else if (isSelfGoods && !isRebate) {//自营并不返现
        return @"[hongziying] ";
    }else if (isRebate && !isSelfGoods) {//不是自营并返现
        return @"[fanxian] ";
    }else if (!isSelfGoods && !isRebate) {//既不是自营也不返现
       return @"";
    }
    return @"";
}
//商品标题拼接
- (NSString *)appendTitle:(NSString*)title imageName:(NSString*)imageName {
    if (imageName.length != 0) {
        return [NSString stringWithFormat:@"%@%@",imageName,title];
    } else {
        return title;
    }
}
//返利或推荐内容
- (NSString *)rebateOrRecommend:(NSString*)type content:(NSString*)content isRebate:(BOOL)isRebate{
    NSString *fuHao = @"%";
    if (isRebate) {//有返利
        if ([type isEqualToString:@"rebate"]) {
            return [NSString stringWithFormat:@"白金会员现在购买，返现%@%@，购物即存钱",[NSString marketLastTwoByteOfStringIsZero:content],fuHao];
            
        }else if ([type isEqualToString:@"recommend"]) {
            return [NSString stringWithFormat:@"现在推荐好友购买，返现%@%@，购物即理财",[NSString marketLastTwoByteOfStringIsZero:content],fuHao];
        }
    } else {//未返利
        return [NSString stringWithFormat:@"推荐好友购买大实惠直营商品,最高返现%@%@,去推荐",[NSString marketLastTwoByteOfStringIsZero:content],fuHao];
    }
    return @"";
}
//处理轮播图
- (NSArray *)handleLoopImagesDatas:(NSArray*)originalImages{
    NSMutableArray *images = [[NSMutableArray alloc]init];
    if (originalImages.count != 0) {
        for (NSInteger i=0; i < originalImages.count; i++) {
            NSString *imageUrl = [NSString stringWithFormat:@"%@%@",baseImageUrl,[NSString stringTransformObject:[originalImages objectAtIndex:i]]];
            [images addObject:imageUrl];
        }
    }else {
        [images addObject:@"productDetail_Default_loopImage"];
    }
    return images;
}
@end
